/**
 * *******************************************
 * user: zmq
 * describe: mysql 数据库驱动脚本
 * created:
 * date: 2021/8/18
 * *******************************************
 */

import * as mysql from "mysql2";
import {logger} from "../../util/logger";

export default class MysqlPool {

    private _pool: any;
    private _promisePool: any;

    /**
     * 构造函数
     * @param mysqlConfig
     * @param modeName
     */
    constructor(mysqlConfig, modeName) {

        let self = this;

        self._pool = mysql.createPool({
            host: mysqlConfig[modeName].host,
            user: mysqlConfig[modeName].user,
            password: mysqlConfig[modeName].password,
            database: mysqlConfig[modeName].database,
            port: mysqlConfig[modeName].port,
            connectionLimit: mysqlConfig[modeName].connectionLimit, // 线程池常规维持上限
        });

        self._promisePool = self._pool.promise();
    }


    /**
     * DB query
     * @param sql
     * @param options
     */
    public async query(sql: string, options: any[]) {

        let self = this;
        let conn = await self._promisePool.getConnection();
        if (!conn.connection) {
            logger.info(`conn.connection error --> `);
            return undefined;
        }

        return  conn.query(sql, options).then((rows, fields) => {
            // TODO 连接释放问题
            conn.connection.release();
            return rows[0];
        }).catch((error) => {
                logger.info(`db error --> `, error);
                return undefined;
        })
    }

    /**
     * DB query
     * @param sql
     * @param options
     * @param callback
     */
    public query2(sql: string, options: any[], callback: Function) {

        this._pool.getConnection((err, conn) => {
            if (err) {
                callback(err, undefined, undefined);
            } else {
                conn.query(sql, options, (err, results, fields) => {
                    // 释放连接会连接池
                    conn.release();
                    // 事件驱动回调
                    callback(err, results, fields);
                });
            }
        });
    }
}

